//
//  SpotViewController.m
//  DYS
//
//  Created by 房 国生 on 15/6/19.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "SpotViewController.h"
#import "SpotTableViewCell.h"
#import "UIButton+WebCache.h"
#import "SpotEntity.h"
#import "CommonService.h"
#import "SpotDetailViewController.h"

#import "PlayerViewController.h"
#import "FSPlaylistItem.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "YYAnimationIndicator.h"

#import "DBManager.h"

#import "DXAlertView.h"
#import "OpenUDID.h"
#import "TCBlobDownloadManager.h"
#import "ZipArchive.h"
@interface SpotViewController () <SpotDelegate, MBProgressHUDDelegate>
{
    MBProgressHUD *HUD;
    YYAnimationIndicator *indicator;
    BOOL downloading;
}
@property (nonatomic,strong) NSMutableArray *arraySpot;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *btnDownLoad;
@property (nonatomic , unsafe_unretained) TCBlobDownloadManager *sharedDownloadManager;
@end
//static NSInteger isSame = 10000 ;

@implementation SpotViewController
@synthesize tableViewSpot, parkEntity,btnDownLoad;
@synthesize mutableArraySpot,arraySpot;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"景点";
    [btnDownLoad setTitle:@"离线音频" forState:UIControlStateNormal];
    downloading = NO;
    _progressView.hidden = YES;
    _progressView.progress = 0;
    self.sharedDownloadManager = [TCBlobDownloadManager sharedDownloadManager];
    
    ParkEntity *entity = [DBManager selectParkByParkId:parkEntity.ID];
    if ([entity.isSpot isEqualToString:@"1"]) {
        CommonService *service = [[CommonService alloc] init];
        if ([service getSpotLocalData:parkEntity.ID ArraySpot:arraySpot] == YES) {
            [btnDownLoad setTitle:@"已下载" forState:UIControlStateNormal];
            [btnDownLoad setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            btnDownLoad.enabled = NO;
            
            [AppDelegate instance].spot_from_local = YES;
        }
    } else {
        [AppDelegate instance].spot_from_local = NO;
//        [self getSpotFromInternetData];
    }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArraySpot count]/2 + ([mutableArraySpot count]%2 > 0 ? 1: 0);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"SpotTableViewCell";
    SpotTableViewCell *cell = (SpotTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SpotTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.spotDelegate = self;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row*2 < [mutableArraySpot count]) {
        SpotEntity *entity = [mutableArraySpot objectAtIndex:indexPath.row*2];
        
        if ([AppDelegate instance].file_from_local == YES) {
            NSString *localImagePath = [CommonService addLocalRootPath:entity.album ParkId:parkEntity.ID];
            DebugLog(@"%@", localImagePath);
            UIImage* img = [UIImage imageWithContentsOfFile:localImagePath];
            [cell.btnLeft setBackgroundImage:img forState:UIControlStateNormal];
        } else {
            [cell.btnLeft sd_setImageWithURL:[NSURL URLWithString:entity.album] forState:UIControlStateNormal];
        }
        if ([entity.is_recommend isEqualToString:@"1"]) {
            [cell.imageLeft setImage:[UIImage imageNamed:@"推荐景点"]];
            cell.imageLeft.hidden = NO;
        }
        cell.btnLeft.tag = indexPath.row*2;
        cell.labelLeft.text = entity.title;
        
        cell.btnLeft.hidden = NO;
        cell.labelLeft.hidden = NO;
//        cell.imageViewAduioLeft.hidden = NO;
       cell.btnLeft.layer.masksToBounds = YES;
        [cell.btnLeft.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
        cell.labelLeft.layer.masksToBounds = YES;
        [cell.labelLeft.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
        cell.imageLeft.layer.masksToBounds = YES;
        [cell.imageLeft.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
        
    }
    
//    if (indexPath.row*2 + 1 < [mutableArraySpot count]) {
//        SpotEntity *entity = [mutableArraySpot objectAtIndex:indexPath.row*2 + 1];
//        
//        if ([AppDelegate instance].file_from_local == YES) {
//            NSString *localImagePath = [CommonService addLocalRootPath:entity.album ParkId:parkEntity.ID];
//            DebugLog(@"%@", localImagePath);
//            UIImage* img = [UIImage imageWithContentsOfFile:localImagePath];
//            [cell.btnMiddle setBackgroundImage:img forState:UIControlStateNormal];
//        } else {
//            [cell.btnMiddle sd_setImageWithURL:[NSURL URLWithString:entity.album] forState:UIControlStateNormal];
//        }
//        
//        cell.btnMiddle.tag = indexPath.row*2 + 1;
//        cell.labelMiddle.text = entity.title;
//        if ([entity.is_recommend isEqualToString:@"1"]) {
//            [cell.imageMiddel setImage:[UIImage imageNamed:@"景点推荐角标"]];
//        }
//        cell.btnMiddle.hidden = NO;
//        cell.labelMiddle.hidden = NO;
//        cell.imageViewAduioMiddel.hidden = NO;
//        cell.imageMiddel.hidden = NO;
//    }
    
    if (indexPath.row*2 + 1 < [mutableArraySpot count]) {
        SpotEntity *entity = [mutableArraySpot objectAtIndex:indexPath.row*2 + 1];
        
        if ([AppDelegate instance].file_from_local == YES) {
            NSString *localImagePath = [CommonService addLocalRootPath:entity.album ParkId:parkEntity.ID];
            DebugLog(@"%@", localImagePath);
            UIImage* img = [UIImage imageWithContentsOfFile:localImagePath];
            [cell.btnRight setBackgroundImage:img forState:UIControlStateNormal];
        } else {
            [cell.btnRight sd_setImageWithURL:[NSURL URLWithString:entity.album] forState:UIControlStateNormal];
        }
        
        cell.btnRight.tag = indexPath.row*2 + 1;
        cell.labelRight.text = entity.title;
        cell.btnRight.hidden = NO;
        cell.labelRight.hidden = NO;
        if ([entity.is_recommend isEqualToString:@"1"]) {
            [cell.imageRight setImage:[UIImage imageNamed:@"推荐景点"]];
            cell.imageRight.hidden = NO;
        }
//        cell.imageViewAduioRight.hidden = NO;
        cell.btnRight.layer.masksToBounds = YES;
        [cell.btnRight.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
        cell.labelRight.layer.masksToBounds = YES;
        [cell.labelRight.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
        cell.imageRight.layer.masksToBounds = YES;
        [cell.imageRight.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 100;
    return ((SCREEN_WIDTH - 30)/2*92/145 +8);
    
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //NewsEntity *entity = [arraySpot objectAtIndex:indexPath.row];
}

- (void)spotButtonAction:(NSInteger) tag {
//    
//    [[AppDelegate instance] showCustomView:NO];
//    
//     if (tag != isSame ){
//        isSame = tag;
//          [AppDelegate instance].spotVC = [[SpotDetailViewController alloc]init];
//     }
//    
//    
//        SpotEntity *entity = [mutableArraySpot objectAtIndex:tag];
//        
//         [AppDelegate instance].spotVC.entity = entity;
//         [AppDelegate instance].spotVC.parkEntity = parkEntity;
//         [AppDelegate instance].spotVC.musicArrayNumber = tag;
//         [AppDelegate instance].spotVC.musicArray = mutableArraySpot;
//    
//         [self.navigationController pushViewController:[AppDelegate instance].spotVC animated:YES];
//    
//        [[AppDelegate instance].spotVC showStausBar];
    
//    [[AppDelegate instance] showCustomView:NO];
//    
//     if (tag != isSame ){
//        isSame = tag;
//          [AppDelegate instance].spotVC = [[SpotDetailViewController alloc]init];
//     }
//    
//    
//        SpotEntity *entity = [mutableArraySpot objectAtIndex:tag];
//        
//         [AppDelegate instance].spotVC.entity = entity;
//         [AppDelegate instance].spotVC.parkEntity = parkEntity;
//         [AppDelegate instance].spotVC.musicArrayNumber = tag;
//         [AppDelegate instance].spotVC.musicArray = mutableArraySpot;
//    
//         [self.navigationController pushViewController:[AppDelegate instance].spotVC animated:YES];
//    
//        [[AppDelegate instance].spotVC showStausBar];
    
    SpotDetailViewController *vc = [SpotDetailViewController sharedInstance];
    
    SpotEntity *entity = [mutableArraySpot objectAtIndex:tag];
    
     vc.entity = entity;
     vc.parkEntity = parkEntity;
     vc.musicArrayNumber = tag;
     vc.musicArray = mutableArraySpot;
    vc.isTap = NO;
    [self.navigationController pushViewController:vc animated:YES];
//
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SpotViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"SpotViewController"];
}
- (IBAction)downLoad:(id)sender {
    if (downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
        return;
    } else {
        [self loadSpotData];
    
    }

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载当前景区离线音频资源包" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    alert.tag = 4444;
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 4444) {
        ;
    }
}
- (BOOL) loadSpotData {
    // 调整示例frame
    NSString *fileName = @"getSource";//[NSString stringWithFormat:@"park_%@.zip",parkEntity.ID ];
    //NSString *aSavePath = @"lyss";
    
    //检查本地文件是否已存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
    parkEntity = [DBManager selectParkByParkId:parkEntity.ID];
    
    
    if ([parkEntity.isSpot isEqualToString:@"1"]) {// && [fileManager fileExistsAtPath:filePath]
        
        CommonService *service = [[CommonService alloc] init];
        
        if ([arraySpot count] == 0) {
            if ([service getSpotLocalData:parkEntity.ID ArraySpot:arraySpot  ] == YES) {
                return YES;
            } else {
                ALERT_ERR_MSG(DownloadCacheSourceFail);
                return NO;
            }
        } else {
            return YES;
        }
    } else {
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"提示"
                                                    contentText:@"下载景区音频资料？"
                                                leftButtonTitle:@"取消"
                                               rightButtonTitle:@"确定"];
        [alert show];
        alert.leftBlock = ^() {
            NSLog(@"left button clicked");
        };
        alert.rightBlock = ^() {
            [self downloadPackage];
        };
        alert.dismissBlock = ^() {
            NSLog(@"Do something interesting after dismiss block");
        };
        return NO;
    }
}
- (void) downloadPackage {
    
    NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
    //NSString *aSavePath = @"lyss";
    
    //检查本地文件是否已存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
//    NSString *fileNameTemp = [NSString stringWithFormat:@"park"];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    
    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
    
//    if (![fileManager fileExistsAtPath:folder]) {
//        BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
//        if (blCreateFolder) {
//            blCreateFolder= [fileManager createDirectoryAtPath:park_path withIntermediateDirectories:NO attributes:nil error:NULL];
//            if (blCreateFolder) {
//                NSLog(@" folder success2");
//            }else {
//                NSLog(@" folder fial2");
//            }
//        } else {
//            
//        }
//        if (blCreateFolder) {
//            NSLog(@" folder success");
//        }else {
//            NSLog(@" folder fial");
//        }
//    } else {
//        NSLog(@" 沙盒文件已经存在");
//    }
//    
    //NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/lysss"];
//    if (![fileManager fileExistsAtPath:filePath]) {
//        _progressView.hidden = NO;
//        _downloading = YES;
       [_progressView setProgress:0];
//        _labelProgress.hidden = NO;
        //判断是否链接LET-FI设备，并试图读取SD卡上的相关内容
        NSString *LET_FI_URL = [NSString stringWithFormat:@"%@/resource/park-%@.zip", LET_FI, parkEntity.ID];
    
    
        [self downloadPackage:LET_FI_URL ParkPath:park_path];
//    DebugLog(@"%@",[self downloadPackage:LET_FI_URL ParkPath:park_path]);
        //        if ([CommonService isExistenceLETFINetwork:LET_FI_URL] == YES) {
        //            [self downloadPackage:LET_FI_URL ParkPath:park_path];
        //        } else {
        //            [self downloadPackage:url ParkPath:park_path];
        //        }
//    } else {
//        NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
//        NSData *data = [file readDataToEndOfFile];//得到xml文件
//        
//        NSString* aStr;
//        aStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];         //转换为NSString
//        NSLog( @"aStr is %@", aStr );
//    }
}
- (BOOL) downloadPackage:(NSString *)url ParkPath:(NSString *)park_path{
    return [self.sharedDownloadManager startDownloadWithURL:[NSURL URLWithString:url]
                                                 customPath:park_path
                                              firstResponse:^(NSURLResponse *response) {
                                                  
                                              }
                                                   progress:^(float receivedLength, float totalLength) {
                                                       downloading = YES;
                                                       NSLog(@"totalBytesRead = %f totalBytesExpectedToRead = %f",receivedLength,totalLength);
                                                       float progress = receivedLength / (float)totalLength;
                                                       _progressView.hidden = NO;
                                                       [_progressView setProgress:progress];
//                                                       _labelProgress.text = [NSString stringWithFormat:@"(%.1f%%)", progress*100.0];
                                                       
                                                       parkEntity.package_size = [NSString stringWithFormat:@"%fM", totalLength/(1024.0*1024)];
                                                   }
                                                      error:^(NSError *error) {
                                                          _progressView.hidden = YES;
//                                                          _labelProgress.hidden = YES;
                                                          downloading = NO;
                                                          NSLog(@"error = %@",error);
                                                          
                                                          if ([url containsString:LET_FI] == YES) {
                                                              UserEntity *user = [UserEntity sharedInstance];
                                                              LocationManagement *lm = [LocationManagement sharedInstance];
                                                              NSString *longitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.longitude ];
                                                              NSString *latitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.latitude ];
                                                              
                                                              NSString *url2 = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@&simple=%@",
                                                                               BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value] ,@"0" ];
                                                              
                                                              if ([url isEqualToString:url2]) {
                                                                  
                                                                  ALERT_ERR_MSG(@"该景区暂无离线音频");
                                                              }
                                                              else
                                                              {
                                                                  [self downloadPackage:url2 ParkPath:park_path];
                                                                  downloading = YES;
                                                              }
                                                              
                                                              
                                                              
                                                          } else {
                                                              ALERT_ERR_MSG(DownloadWebsiteSourceFail);
                                                          }
                                                      }
                                                   complete:^(BOOL downloadFinished, NSString *pathToFile) {
                                                       _progressView.hidden = YES;
//                                                       _labelProgress.hidden = YES;
                                                       
                                                       //定义一个布尔类型的对象
                                                       BOOL ifsucess;
                                                       //在objective－c种，正确是YES 错误是NO
                                                       ifsucess = NO;
                                                       //获取上面fileData对象中通过NSFileManager对象获取的文件中的内容，然后再创建一个新的路径，并存储
                                                       
                                                       //                                                    if (operation.responseData != nil) {
                                                       //                                                        DebugLog(@"%@", @"operation.responseData not nil");
                                                       //                                                    }
                                                       //                                                    ifsucess = [fileManager createFileAtPath:filePath contents:operation.responseData attributes:nil];
                                                       NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:pathToFile];
                                                       NSData *data = [file readDataToEndOfFile];//得到xml文件
                                                       //对布尔型对象进行判断
                                                       if(data) {
                                                           NSLog(@"create file sucess");
                                                           //we need save this data to the sqlite
                                                           parkEntity.local_path = pathToFile;
                                                           
                                                           //解压压缩包
                                                           ZipArchive *za = [[ZipArchive alloc] init];
                                                           if ([za UnzipOpenFile: pathToFile]) {
                                                               BOOL ret = [za UnzipFileTo:park_path overWrite: YES];
                                                               if (NO == ret){
                                                                   NSLog(@"za UnzipFileTo fail");
                                                                   ALERT_ERR_MSG(@"解压失败");
                                                               } else {
                                                                   ALERT_ERR_MSG(@"解压成功");
                                                                   
                                                                   //删除压缩包文件
                                                                   [CommonService deleteFile:pathToFile];
                                                                   //获取文件夹的大小
                                                                   parkEntity.package_size = [CommonService getFolderSize:parkEntity.ID];
                                                                   [btnDownLoad setTitle:@"已下载" forState:UIControlStateNormal];
                                                                   [btnDownLoad setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                                                                   btnDownLoad.enabled = NO;
                                                                   [[DBManager createDataBase] open];
                                                                   parkEntity = [DBManager selectParkByParkId:parkEntity.ID];
                                                                   parkEntity.isSpot = @"1";
                                                                   [DBManager UpdataParkEntity:parkEntity];
                                                                   
                                                                   CommonService *service = [[CommonService alloc] init];
                                                                   //                                                            if ([service getSpotDataFromLocal:self.parkId
                                                                   //                                                                                    ArraySpot:arraySpot
                                                                   //                                                                                ArrayBusiness:arrayBusiness
                                                                   //                                                                                  ArrayToilet:arrayToilet
                                                                   //                                                                                ArrayRoadLine:arrayRoadLine
                                                                   //                                                                                   ParkEntity:parkEntity] == YES) {
                                                                   //                                                                ALERT_ERR_MSG(@"景区资料下载完成");;
                                                                   //                                                            } else {
                                                                   //                                                                ALERT_ERR_MSG(@"加载本地资源失败");
                                                                   //                                                            }
                                                               }
                                                               [za UnzipCloseFile];
                                                           } else {
                                                               
                                                           }
                                                       } else {
                                                           if ([url containsString:LET_FI] != YES) {
                                                               ALERT_ERR_MSG(DownloadFail);
                                                           }
                                                       }
                                                       downloading = NO;
                                                   }];
}
@end



